import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/patientPage',
      component: () => import('../views/user//patientPage.vue'),
      meta: { title: '患者档案' }
    },
    {
      path: '/login',
      component: () => import('../views/login/index.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/',
      redirect: '/home',
      component: () => import('../views/layout/index.vue'),
      children: [
        {
          path: '/home',
          component: () => import('../views/home/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: '/article',
          component: () => import('../views/article/index.vue'),
          meta: { title: '健康百科' }
        },
        {
          path: '/notify',
          component: () => import('../views/notify/index.vue'),
          meta: { title: '消息中心' }
        },
        {
          path: '/user',
          component: () => import('../views/user/index.vue'),
          meta: { title: '我的页面' }
        }
      ]
    }
  ]
})
// 进度条 小圆圈
NProgress.configure({
  showSpinner: false
})
// 全局导航守卫
router.beforeEach((to) => {
  NProgress.start()
  // 获取token
  const store = useUserStore()
  // 白名单
  const whiteList = ['/login']
  // 如果你没有token并且不在白名单里面，重定向登录
  if (!store.user?.token && !whiteList.includes(to.path)) return '/login'
})

// 全局导航后置守卫
router.afterEach((to) => {
  // 页面加载出来以后，再弹出标题
  document.title = `${to.meta.title || ''}-优医问诊`
  NProgress.done()
})
export default router
